<template>
  <div class="repositories">
    <div class="page-header">
      <div class="header-left">
        <h1>仓库管理</h1>
        <p class="subtitle">管理您的容器镜像和制品仓库</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          创建仓库
        </el-button>
      </div>
    </div>

    <!-- Search and Filter -->
    <div class="search-section">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索仓库名称..."
          prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
      </div>
      <div class="filter-bar">
        <el-select v-model="sortBy" placeholder="排序方式" @change="loadRepositories">
          <el-option label="创建时间" value="createdAt" />
          <el-option label="更新时间" value="updatedAt" />
          <el-option label="下载次数" value="downloadCount" />
          <el-option label="名称" value="name" />
        </el-select>
        <el-select v-model="sortOrder" placeholder="排序顺序" @change="loadRepositories">
          <el-option label="降序" value="desc" />
          <el-option label="升序" value="asc" />
        </el-select>
      </div>
    </div>

    <!-- Repositories List -->
    <div v-loading="loading" class="repositories-content">
      <div v-if="repositories.length === 0 && !loading" class="empty-state">
        <el-icon><Box /></el-icon>
        <h3>暂无仓库</h3>
        <p>创建您的第一个仓库开始使用</p>
        <el-button type="primary" @click="showCreateDialog = true">
          创建仓库
        </el-button>
      </div>

      <div v-else class="repositories-grid">
        <el-card 
          v-for="repo in repositories" 
          :key="repo.id" 
          class="repository-card"
          shadow="hover"
          @click="goToRepository(repo.name)"
        >
          <div class="repo-header">
            <div class="repo-info">
              <h3 class="repo-name">{{ repo.name }}</h3>
              <p class="repo-description">{{ repo.description || '暂无描述' }}</p>
            </div>
            <el-dropdown @command="handleRepoAction" @click.stop>
              <el-button type="text" class="action-button">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'edit', repo }">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', repo }" divided>
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <div class="repo-stats">
            <div class="stat-item">
              <el-icon><Files /></el-icon>
              <span>{{ repo.artifactCount || 0 }} 制品</span>
            </div>
            <div class="stat-item">
              <el-icon><Download /></el-icon>
              <span>{{ repo.downloadCount || 0 }} 下载</span>
            </div>
            <div class="stat-item">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(repo.updatedAt) }}</span>
            </div>
          </div>

          <div class="repo-tags">
            <el-tag v-if="repo.isPublic" type="success" size="small">公开</el-tag>
            <el-tag v-else type="info" size="small">私有</el-tag>
          </div>
        </el-card>
      </div>
    </div>

    <!-- Pagination -->
    <div v-if="total > pageSize" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadRepositories"
        @current-change="loadRepositories"
      />
    </div>

    <!-- Create Repository Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建仓库"
      width="500px"
      @close="resetCreateForm"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-width="80px"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input
            v-model="createForm.name"
            placeholder="请输入仓库名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入仓库描述（可选）"
          />
        </el-form-item>
        <el-form-item label="访问权限">
          <el-radio-group v-model="createForm.isPublic">
            <el-radio :label="true">公开</el-radio>
            <el-radio :label="false">私有</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="createLoading" @click="handleCreate">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- Edit Repository Dialog -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑仓库"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="仓库名称">
          <el-input v-model="editForm.name" disabled />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入仓库描述（可选）"
          />
        </el-form-item>
        <el-form-item label="访问权限">
          <el-radio-group v-model="editForm.isPublic">
            <el-radio :label="true">公开</el-radio>
            <el-radio :label="false">私有</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleEdit">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Plus,
  Search,
  Box,
  Files,
  Download,
  Clock,
  MoreFilled,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import type { Repository } from '@/types/api'

const router = useRouter()

const repositories = ref<Repository[]>([])
const loading = ref(false)
const searchQuery = ref('')
const sortBy = ref('updatedAt')
const sortOrder = ref('desc')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const createLoading = ref(false)
const editLoading = ref(false)

const createFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

const createForm = reactive({
  name: '',
  description: '',
  isPublic: true
})

const editForm = reactive({
  id: '',
  name: '',
  description: '',
  isPublic: true
})

const createRules: FormRules = {
  name: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '仓库名称长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-z0-9]([a-z0-9._-]*[a-z0-9])?$/, message: '仓库名称只能包含小写字母、数字、点、下划线和连字符', trigger: 'blur' }
  ]
}

const editRules: FormRules = {
  description: [
    { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

const formatTime = (time: string): string => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes} 分钟前`
  } else if (hours < 24) {
    return `${hours} 小时前`
  } else if (days < 7) {
    return `${days} 天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const loadRepositories = async () => {
  loading.value = true
  try {
    // TODO: Implement API call to get repositories
    // const response = await getRepositories({
    //   page: currentPage.value,
    //   size: pageSize.value,
    //   search: searchQuery.value,
    //   sortBy: sortBy.value,
    //   sortOrder: sortOrder.value
    // })
    // repositories.value = response.data.items
    // total.value = response.data.total
    
    // Mock data for now
    repositories.value = [
      {
        id: '1',
        name: 'nginx',
        description: 'High-performance web server',
        isPublic: true,
        downloadCount: 500,
        artifactCount: 12,
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7).toISOString(),
        updatedAt: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString()
      },
      {
        id: '2',
        name: 'redis',
        description: 'In-memory data structure store',
        isPublic: false,
        downloadCount: 300,
        artifactCount: 8,
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 5).toISOString(),
        updatedAt: new Date(Date.now() - 1000 * 60 * 60 * 6).toISOString()
      }
    ]
    total.value = 2
  } catch (error) {
    ElMessage.error('加载仓库列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadRepositories()
}

const goToRepository = (name: string) => {
  router.push(`/repositories/${name}`)
}

const handleRepoAction = async (command: { action: string; repo: Repository }) => {
  const { action, repo } = command
  
  if (action === 'edit') {
    editForm.id = repo.id
    editForm.name = repo.name
    editForm.description = repo.description || ''
    editForm.isPublic = repo.isPublic || false
    showEditDialog.value = true
  } else if (action === 'delete') {
    try {
      await ElMessageBox.confirm(
        `确定要删除仓库 "${repo.name}" 吗？此操作不可恢复。`,
        '确认删除',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      // TODO: Implement API call to delete repository
      // await deleteRepository(repo.id)
      
      ElMessage.success('仓库删除成功')
      loadRepositories()
    } catch (error) {
      // User cancelled or error occurred
    }
  }
}

const handleCreate = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    createLoading.value = true
    
    // TODO: Implement API call to create repository
    // await createRepository(createForm)
    
    ElMessage.success('仓库创建成功')
    showCreateDialog.value = false
    resetCreateForm()
    loadRepositories()
  } catch (error: any) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('创建仓库失败，请重试')
    }
  } finally {
    createLoading.value = false
  }
}

const handleEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    // TODO: Implement API call to update repository
    // await updateRepository(editForm.id, editForm)
    
    ElMessage.success('仓库更新成功')
    showEditDialog.value = false
    resetEditForm()
    loadRepositories()
  } catch (error: any) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('更新仓库失败，请重试')
    }
  } finally {
    editLoading.value = false
  }
}

const resetCreateForm = () => {
  createForm.name = ''
  createForm.description = ''
  createForm.isPublic = true
  createFormRef.value?.resetFields()
}

const resetEditForm = () => {
  editForm.id = ''
  editForm.name = ''
  editForm.description = ''
  editForm.isPublic = true
  editFormRef.value?.resetFields()
}

onMounted(() => {
  loadRepositories()
})
</script>

<style scoped>
.repositories {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
}

.search-bar {
  flex: 1;
  max-width: 400px;
}

.filter-bar {
  display: flex;
  gap: 12px;
}

.repositories-content {
  min-height: 400px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #c0c4cc;
}

.empty-state .el-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #909399;
}

.empty-state p {
  margin: 0 0 16px 0;
  color: #c0c4cc;
}

.repositories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.repository-card {
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.repository-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.repo-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.repo-info {
  flex: 1;
}

.repo-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.repo-description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.4;
}

.action-button {
  padding: 4px;
  color: #909399;
}

.repo-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.repo-tags {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-bar {
    justify-content: stretch;
  }
  
  .filter-bar .el-select {
    flex: 1;
  }
  
  .repositories-grid {
    grid-template-columns: 1fr;
  }
}
</style>